home *** CD-ROM | disk | FTP | other *** search
/ BCI NET 2 / BCI NET 2.iso / archives / programming / source / graphicgems4.lha / GemsIV / centroid.c next >
Encoding:
Text File  |  1995-02-06  |  1.4 KB  |  43 lines

  1. /*
  2.  * ANSI C code from the article
  3.  * "Centroid of a Polygon"
  4.  * by Gerard Bashein and Paul R. Detmer,
  5.     (gb@locke.hs.washington.edu, pdetmer@u.washington.edu)
  6.  * in "Graphics Gems IV", Academic Press, 1994
  7.  */
  8.  
  9. /*********************************************************************
  10. polyCentroid: Calculates the centroid (xCentroid, yCentroid) and area
  11. of a polygon, given its vertices (x[0], y[0]) ... (x[n-1], y[n-1]). It
  12. is assumed that the contour is closed, i.e., that the vertex following
  13. (x[n-1], y[n-1]) is (x[0], y[0]).  The algebraic sign of the area is
  14. positive for counterclockwise ordering of vertices in x-y plane;
  15. otherwise negative.
  16.  
  17. Returned values:  0 for normal execution;  1 if the polygon is
  18. degenerate (number of vertices < 3);  and 2 if area = 0 (and the
  19. centroid is undefined).
  20. **********************************************************************/
  21. int polyCentroid(double x[], double y[], int n,
  22.          double *xCentroid, double *yCentroid, double *area)
  23.      {
  24.      register int i, j;
  25.      double ai, atmp = 0, xtmp = 0, ytmp = 0;
  26.      if (n < 3) return 1;
  27.      for (i = n-1, j = 0; j < n; i = j, j++)
  28.       {
  29.       ai = x[i] * y[j] - x[j] * y[i];
  30.       atmp += ai;
  31.       xtmp += (x[j] + x[i]) * ai;
  32.       ytmp += (y[j] + y[i]) * ai;
  33.       }
  34.      *area = atmp / 2;
  35.      if (atmp != 0)
  36.       {
  37.       *xCentroid =    xtmp / (3 * atmp);
  38.       *yCentroid =    ytmp / (3 * atmp);
  39.       return 0;
  40.       }
  41.      return 2;
  42.      }
  43.